//
//  WGS84ToGCJ02.m
//  Lrjh
//
//  Created by jun on 2025/7/21.
//

#import "WGS84ToGCJ02.h"

const double a = 6378245.0; // 地球长半轴
const double ee = 0.00669342162296594323; // 扁率

@implementation WGS84ToGCJ02


+ (CLLocationCoordinate2D)transformFromWGS84ToGCJ02:(CLLocationCoordinate2D)wgs84Coord {
    if ([self isLocationOutOfChina:wgs84Coord]) {
        return wgs84Coord; // 海外坐标无需转换
    }
    double dLat = [self transformLatWithX:wgs84Coord.longitude - 105.0 Y:wgs84Coord.latitude - 35.0];
    double dLon = [self transformLonWithX:wgs84Coord.longitude - 105.0 Y:wgs84Coord.latitude - 35.0];
    double radLat = wgs84Coord.latitude / 180.0 * M_PI;
    double magic = sin(radLat);
    magic = 1 - ee * magic * magic;
    double sqrtMagic = sqrt(magic);
    dLat = (dLat * 180.0) / ((a * (1 - ee)) / (magic * sqrtMagic) * M_PI);
    dLon = (dLon * 180.0) / (a / sqrtMagic * cos(radLat) * M_PI);
    
    CLLocationCoordinate2D gcj02Coord = CLLocationCoordinate2DMake(wgs84Coord.latitude + dLat, wgs84Coord.longitude + dLon);
    return gcj02Coord;
}

// 判断是否在国内（中国矩形区域）
+ (BOOL)isLocationOutOfChina:(CLLocationCoordinate2D)coord {
    return !(coord.longitude > 72.004 && coord.longitude < 137.8347 &&
             coord.latitude > 0.8293 && coord.latitude < 55.8271);
}

// 纬度转换计算
+ (double)transformLatWithX:(double)x Y:(double)y {
    double lat = -100.0 + 2.0 * x + 3.0 * y + 0.2 * y * y + 0.1 * x * y + 0.2 * sqrt(fabs(x));
    lat += (20.0 * sin(6.0 * x * M_PI) + 20.0 * sin(2.0 * x * M_PI)) * 2.0 / 3.0;
    lat += (20.0 * sin(y * M_PI) + 40.0 * sin(y / 3.0 * M_PI)) * 2.0 / 3.0;
    return lat;
}

// 经度转换计算
+ (double)transformLonWithX:(double)x Y:(double)y {
    double lon = 300.0 + x + 2.0 * y + 0.1 * x * x + 0.1 * x * y + 0.1 * sqrt(fabs(x));
    lon += (20.0 * sin(6.0 * x * M_PI) + 20.0 * sin(2.0 * x * M_PI)) * 2.0 / 3.0;
    lon += (20.0 * sin(x * M_PI) + 40.0 * sin(x / 3.0 * M_PI)) * 2.0 / 3.0;
    return lon;
}

@end
